package com.springbootdf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springbootdf.Dto.UserDto;
import com.springbootdf.common.Constants;
import com.springbootdf.entity.User;
import com.springbootdf.exception.ServiceException;
import com.springbootdf.mapper.UserMapper;
import com.springbootdf.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springbootdf.utils.TokenUtils;
import org.springframework.stereotype.Service;

import static cn.hutool.core.lang.Console.log;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wy
 * @since 2022-08-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public UserDto login(UserDto userDto) {
        User user = getUserInfo(userDto);
        if (user != null){
            BeanUtil.copyProperties(user,userDto,true);
            String token = TokenUtils.genToken(user.getId().toString(), user.getPassword());
            userDto.setToken(token);
            return userDto;
        }else {
            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }
    }

    @Override
    public User register(UserDto userDTO) {
        User one=getUserInfo(userDTO);
        if( one == null){
            one = new User();
            BeanUtil.copyProperties(userDTO,one,true);

            save(one);
        }else{
            throw new  ServiceException(Constants.CODE_600,"用户已存在");
        }
        return one;
    }

    private User getUserInfo(UserDto userDto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userDto.getUserName());
        queryWrapper.eq("password",userDto.getPassword());
        User user;
        try {
            user=getOne(queryWrapper);
        }catch (Exception e){
            log(e);
            throw new ServiceException(Constants.CODE_600,"系统错误");
        }
        return user;
    }
}
